<?php


use Illuminate\Support\Env;


// 获取 runtime 路径地址
function getRuntimePath()
{
    return app()->basePath().DIRECTORY_SEPARATOR.'Runtime'.DIRECTORY_SEPARATOR;
}

// $num为生成汉字的数量
function getChar($num)
{
    $str = '';
    for($i = 0; $i < $num; $i++){
        // 使用chr()函数拼接双字节汉字，前一个chr()为高位字节，后一个为低位字节
        $a   = chr(mt_rand(0xB0, 0xD0)).chr(mt_rand(0xA1, 0xF0));
        $str .= iconv('GB2312', 'UTF-8', $a); // 转码
    }

    return $str;
}

// 伪静态链接：英文网站 atw 专用
function atwUrl($type, $parameters = [], $page = 1)
{
    $url = request()->getSchemeAndHttpHost()."/";
    if(('http://localhost/' == $url) || ('https://api.asiatechwire.com/' == $url)){
        $url = Env::get('APP_HOST');
    }
    if($parameters){
        if(empty($parameters['link'])){
            // 组合
            $string  = $parameters['en_title'] ?: $parameters['en_description'];
            $string  = makeAtwArticleLinkTitle($string);
            $strings = explode(" ", $string);
            $urlStr  = $_comm = '';
            foreach($strings as $_key => $_str){
                // 3-4个单词
                $_str = trim($_str);
                if($_str && ($_key < 3)){
                    $urlStr .= $_comm.$_str;
                    $_comm  = '-';
                }
            }

            // 最后组合
            if($type == 'article'){
                $url = $url.$type."-".$urlStr."-".$parameters['id'];
            } else{
                $url = $url.$type."-".$urlStr;
            }
        } else{
            $url = $url.$parameters['link'];
        }
    } else{
        $url = $url.$type;
    }

    if($page > 1){
        $url = $url.'-'.$page;
    }

    return $url.".html";
}


// 构建文章链接
function atwArticleLink($title, $id = null)
{
    if(empty($title)){
        return $id;
    }

    // 特定的操作（Frontend下的所有的控制器）不能使用
    $title  = makeAtwArticleLinkTitle($title);
    $titles = explode(' ', $title);
    if(in_array($titles[0], ['cate', 'tags', 'search', 'email', 'article', 'site'])){
        unset($titles[0]);
    }

    return implode('-', $titles);
}

// 构建链接的
function makeAtwArticleLinkTitle($title)
{
    // 特殊字符处理 @%#！&*’
    /*$not    = ['\'', '"', '-', '—', '.', '…', '_', '-', ':', '：', '(', ')', '（', '）', '.', '。', ',', '，', '；', ';', '*', '&', '!', '?', '？', '#', '！', '$', '%', '@'];
    $string = str_replace($not, '', $title);
    $string = str_replace('@', '', $string);
    $string = str_replace('%', '', $string);
    $string = str_replace('！', '', $string);
    $string = str_replace('#', '', $string);
    $string = str_replace('!', '', $string);
    $string = str_replace('&', '', $string);
    $string = str_replace('*', '', $string);
    $string = str_replace('\'', '', $string);*/

    $string = "";
    for($i = 0; $i < strlen($title); $i++){
        $char = $title[$i];
        if(ctype_alnum($char) || ctype_space($char)){
            $string .= $char;
        }
    }

    return trim($string);
}

// 翻页链接
function pageUrl($url, $page = 0)
{
    $url = url($url);
    if($page){
        if(strpos($url, '?') === false){
            $url = $url.'?page='.$page;
        } else{
            $url = $url.'&page='.$page;
        }
    }

    return $url;
}

// 匿名展示
function anony($user_name)
{
    $strlen   = mb_strlen($user_name, 'utf-8'); //获取字符长度
    $firstStr = mb_substr($user_name, 0, 1, 'utf-8');  //查找字符第一个
    $str      = $firstStr.str_repeat('*', $strlen - 1);  //拼接第一个+把字符串 "* " 重复 $strlen - 1 次：

    return $str;
}

// 从内容中提取图片
function getImage4content($content)
{
    //preg_match_all('/<[\s]*img.*?src=[\'|"|\s]*(.+?|\ )[\'|"|\s|>]/is', $content, $matches);
    preg_match_all('/<[\s]*[img|IMG].*?src=[\'|"|\s]*(.+?|\ )[\'|"|\s|>]/is', $content, $matches);
    $aryimg = array();
    if($matches[1]){
        for($j = 0; $j < count($matches[1]); $j++){
            // 判断是后缀，如果是表情  则不添加
            $_url = $matches[1][$j];
            $ext  = pathinfo($_url, PATHINFO_EXTENSION);
            if($ext == 'gif'){
                continue;
            }

            $aryimg[] = $_url;
        }
    }

    return $aryimg; //$matches[1][$j][0] //返回第一个匹配的图
}

// 生成随机字符串
function random($num = 4)
{
    // 去掉了 0 1 O l 等
    $str   = "23456789abcdefghijkmnpqrstuvwxyz";  //ABCDEFGHIJKLMNPQRSTUVW 不要在写的
    $str   = "1234567890";  //ABCDEFGHIJKLMNPQRSTUVW 不要在写的
    $code  = '';
    $lenth = strlen($str);
    for($i = 0; $i < $num; $i++){
        $code .= $str[mt_rand(0, $lenth - 1)];
    }

    return $code;
}

// 获取默认图片
function getRealImage($img)
{
    $img = $img ?: Env::get('STYLE_HOST').'src/img/default.ico';

    return $img;
}


function timeAgo($time)
{
    if(empty($time)){
        return '';
    }

    $left = LARAVEL_TIME - $time;
    $all  = [
        '31536000' => '年',
        '2592000'  => '月',
        '604800'   => '星期',
        '86400'    => '天',
        '3600'     => '小时',
        '60'       => '分钟',
        '1'        => '秒',
    ];

    // 大于年 显示年月
    $str = '';
    if($left > 31536000){
        $year = floor($left / 31536000);
        $mon  = floor(($left - $year * 31536000) / 2592000);
        $str  = $year.'年';
        if($mon){
            $str .= $mon.'月';
        }
    } elseif($left > 2592000){
        // 大于年 显示月
        $str = floor($left / 2592000).'月';
    } elseif($left > 86400){
        // 大于天 显示天
        $str = floor($left / 86400).'天';
    } else{
        if(LARAVEL_TIME - strtotime(date('Y-m-d')) > $left){
            $str = '今天';
        } else{
            $str = '昨天';
        }
    }

    return $str;
}

// 改变图片路径
function replaceUrl($img_url)
{
    $domain    = env('STYLE_HOST');
    $oldDomain = env('OLD_HOST');

    return str_replace($domain, $oldDomain, $img_url);
}

// 样式表
function sass($path, $type = 'pc')
{
    $type  = $type == 'pc' ? 'pc' : 'wap';
    $ds    = DIRECTORY_SEPARATOR;
    $base  = app()->basePath().$ds;
    $style = $base.'public'.$ds.'static'.$ds.$type.$ds;
    $form  = $base.$path;
    $file  = basename($form);
    $to    = $style.$file;
    if(!file_exists($to) || (filemtime($form) > @filemtime($to))){
        $data = file_get_contents($form);
        file_put_contents($to, $data);
    }

    echo '<link type="text/css" href="/static/'.$type.'/'.$file.'" rel="stylesheet" />';
}

// js
function scripts($path, $type = 'pc')
{
    $type  = $type == 'pc' ? 'pc' : 'wap';
    $ds    = DIRECTORY_SEPARATOR;
    $base  = app()->basePath().$ds;
    $style = $base.'public'.$ds.'static'.$ds.$type.$ds;
    $form  = $base.$path;
    $file  = basename($form);
    $to    = $style.$file;
    if(!file_exists($to) || (filemtime($form) > @filemtime($to))){
        $data = file_get_contents($form);
        file_put_contents($to, $data);
    }

    echo '<script type="text/javascript" src="/static/'.$type.'/'.$file.'"></script>';
}

// nginx的404
function nginx404()
{
    return '<html><head><title>404 Not Found</title></head><body bgcolor="white"><center><h1>404 Not Found</h1></center><hr><center>nginx</center></body></html>';
}
